# calculate the pvalues of each regression parameters
# 
# @fittedModel: an 'agModeling' object or its extensions.
# @kappa: numeric parameter for Thomas process. For LGCP, kappa is correspondence to sigma2
# @omega: numeric parameter for Thomas process, For LGCP, omega is correspondence to alpha
# 
# Author: guochun
###############################################################################
library(InhomCluster)

confi.inter=function(fittedModel,kappa,omega){
	covr=fittedModel@covr
	ncol=length(covr)+1
	beta=coef(attr(fittedModel,"re.ppm"))
	
#step 1: constructe covaraince matrix z
	nrow=length(covr[[1]]$v)
	z=matrix(ncol=ncol,nrow=nrow)
	z[,1]=rep(1,times=nrow)
	for (i in 2:ncol){
		z[,i]=as.vector(covr[[i-1]]$v)
	}
	
#step 2: constructe srule
	dim.covr=covr[[1]]$dim
	plotdim=c(covr[[1]]$xrange[2],covr[[1]]$yrange[2])
	#by.n=plotdim[1]/dim.covr[2]
	grid=expand.grid(covr[[1]]$xcol,covr[[1]]$yrow)
	srule=list(x=grid[,2],y=grid[,1],w=rep(prod(plotdim)/prod(dim.covr),times=prod(dim.covr)))
	
#step 3: constructe grule
	# here, we dicide the size of gride by omega/4, but not smaller than 1 
	# and the extend length is 4*omega
	grid.size=omega/4
	if(grid.size<1)
		grid.size=1
	gx.max=ceiling((8*omega+plotdim[1])/grid.size)
	gy.max=ceiling((8*omega+plotdim[2])/grid.size)
	grid=expand.grid(c(0:(gy.max-1))*grid.size-4*omega,c(0:(gx.max-1))*grid.size-4*omega)
	grule=list(x=grid[,2],y=grid[,1],w=rep(grid.size^2,gx.max*gy.max))
	#grid=expand.grid((c(0:199)-30)*4,(c(0:324)-30)*4)
	#grule=list(x=grid[,2],y=grid[,1],w=rep(800*1300/(200*325),325*200))
	
#step4 : using Asymptotic covariance matrix to calculate sd
	#dneigb=max(modelingObject@population@plotdim)
	#browser()
	dneigb=10
    acacov=inhom.asympcov(z,beta,srule,grule,dneigb,kappa,omega,LGCP=TRUE)
	#acacov=jointasycov(nsim,beta,log(kappa),log(omega),z,srule,
	#		plotdom[1],plotdim[2],1,100,0.25,prod(plotdim))
	#confint(c(beta,log(kappa),log(omega),sqrt(acacov$asycov)))		
    #step5: calculate pvalue
    pval=2*(1-pnorm(abs(beta/sqrt(diag(acacov$asycov)[1:length(beta)]))))
	
	for (i in 2:ncol){
		fittedModel@parameters[[i]]@pvalue=pval[i]
	}
return(fittedModel)
}

